// 引入字体图标样式;
require("../../assets/fonts/iconfont.css");
// 引入axios;
const axios = require("../../assets/js/axios.js");
// 引入自定义js;
let obj = require("../../assets/js/my.js");
let $ = obj.$;
let local = obj.local;
// 引入自己的样式;
require("./sports_course_training.less");
window.addEventListener("load", function () {
	let startTime = Date.now();
	let duration = 0;
	//蒙城数据渲染
	const res = local.getItem("fragments");
	// 页面数据渲染
	$("#totalPart").textContent = res.length;
	// console.log(res);
	// 定义全局的索引
	let index = 1;
	let timeId = null;
	// 自动播放的函数
	function play() {
		// 先关闭上一个定时器
		clearInterval(timeId);
		$("#cerpart").textContent = index;
		$(".part #title").textContent = res[index - 1].title;
		$("#video").src = axios.defaults.baseURL + res[index - 1].videoUrl;
		$("#video").play();
		calcProcress();
	}
	play();
	// 播放结束自动播放
	$("#video").addEventListener("ended", function () {
		++index > res.length ? (index = res.length) : play();
	});
	// 下一页
	$("#nextBtn").addEventListener("click", function () {
		++index > res.length ? (index = res.length) : play();
	});
	// 上一页
	$("#preBtn").addEventListener("click", function () {
		--index < 1 ? (index = 1) : play();
	});
	// 暂停播放并开启蒙城
	$("#stopBtn").addEventListener("click", function () {
		$("#video").pause();
		$("#currentImg").src = axios.defaults.baseURL + res[index - 1].imgUrl;
		$("#currentTitle").textContent = res[index - 1].title;
		$("#mask").style.display = "block";
		duration += Date.now() - startTime;
		// console.log(duration);
	});
	// 继续训练
	$("#btnContinue").addEventListener("click", function () {
		$("#mask").style.display = "none";
		video.play();
		startTime = Date.now();
	});
	//结束训练
	$("#btnOver").addEventListener("click", function () {
		//清除定时器
		clearInterval(timeId);
		// 发送请求
		duration = Math.floor((Date.now() - startTime) / 1000);
		let calorie = Math.ceil(duration * (Math.random() * 0.5 + 1));
		axios
			.post("/api/exercise/save", {
				type: 2,
				duration,
				calorie,
			})
			.then((res) => {
				alert("训练结束,本次消耗" + calorie + "卡路里");
				location.href = "./sports_course.html";
			});
	});
	// 进度条函数的实现
	function calcProcress() {
		timeId = setInterval(() => {
			let currentTime = $("#video").currentTime;
			let totalTime = $("video").duration;
			if (currentTime && totalTime) {
				$("#progress").style.width =
					(currentTime / totalTime) * document.body.clientWidth + "px";
			}
		}, 30);
	}
});
